# !/usr/bin/env python
# encoding: utf-8


"""
  @author: gaogao
  @file: check_equip_comm_thread.py
  @time: 2022/7/31 17:04
  @desc:
"""

import pyvisa as visa
from PyQt5.QtCore import QObject, pyqtSignal, QThread
import time
from ping3 import ping, verbose_ping
from utils.log_util import loggings


class CheckEquipCommTask(QObject):
    result_signal = pyqtSignal(object)
    finished_signal = pyqtSignal()

    def __init__(self, equip_list):
        super().__init__()
        self.equip_list = equip_list

    def run(self):
        for equip in self.equip_list:
            if equip[1].startswith("192"):
                ping_result = ping(equip[1])
                time.sleep(0.2)
                if ping_result is not None:
                    self.result_signal.emit({equip[0].split("_")[0]: "success"})
                else:
                    self.result_signal.emit({equip[0].split("_")[0]: "failed"})
            elif equip[1].endswith("SOCKET"):
                try:
                    inst = visa.ResourceManager().open_resource(equip[1])
                    inst.read_termination = '\n'
                    inst.write_termination = '\n'
                    visa_result = inst.query("*IDN?")
                except Exception as e:
                    loggings.error("CheckEquipCommTask" + str(e))
                    visa_result = ""
                    continue
                finally:
                    if visa_result is not None and visa_result != "":
                        self.result_signal.emit({equip[0].split("_")[0]: "success"})
                    else:
                        self.result_signal.emit({equip[0].split("_")[0]: "failed"})
            else:
                try:
                    inst = visa.ResourceManager().open_resource(equip[1])
                    visa_result = inst.query("*IDN?")
                except Exception as e:
                    loggings.error("CheckEquipCommTask" + str(e))
                    visa_result = ""
                    continue
                finally:
                    if visa_result is not None and visa_result != "":
                        self.result_signal.emit({equip[0].split("_")[0]: "success"})
                    else:
                        self.result_signal.emit({equip[0].split("_")[0]: "failed"})
            QThread.sleep(1)

        else:
            self.finished_signal.emit()
